import isEmpty from 'loadsh/isEmpty'
import { GetInfoPicture, GetPreviewImage, GetProcurementConfirmationInfo, PostDeleteData, PostInfoPicture, PostProcurementConfirmationInfo } from '/constData/requestFun/_httpRequest';
import { GetProcurementConfirmation, GetProcurementConfirmationById, GetPurchaseRequest, GetPurchaseRequestById, PostProcurementConfirmation, ProcurementConfirmationDeleteData } from '/constData/requestFun/_teseRequest';
import compact from 'loadsh/compact'
import { CORPID, SPACEID } from '/constData/requestFun/_globalData';
Page({
  data: {
    Procurement: [
      { value: '办公用品', label: '办公用品' },
      { value: '日常用品', label: '日常用品' },
      { value: '其他用品', label: '其他用品' },
    ],
    Payment: [
      { value: '公司对公司付款', label: '公司对公司付款' },
      { value: '个人对公司付款', label: '个人对公司付款' },
      { value: '其他付款', label: '其他付款' },
    ],
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: null,
    purchaseinfo: {
      CorpId: '',//申请人
      Description: '',//采购项目说明
      ProcurType: '办公用品',//采购类型
      DeliveryTime: '',//交付时间
      ProcurementDetails: '', //采购明细
      ProcurName: '',//名称
      PurchaseQuantity: '',//数量
      Sum:'',
      Unit: '',//单位
      UnitPrice: '', //单价
      PaymentMethod: '公对公', //支付方式
      AssociateOtherId: '[]',//关联ID
      Annex: '[]'//采购结果报告
    },
    displaydata: [],
    ReceiveData: [],

    position: '',
    animation: true,
    basicVisible: false,
    closeVisible: false,
    DisProcurementData: [],
    DisprocurementDisplayData: [],
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    ProcurementConfirmationDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },

  selectorProject(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.purchaseinfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      DisprocurementDisplayData: [...this.data.DisprocurementDisplayData, data],
      purchaseinfo: {
        ...this.data.purchaseinfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
    console.log('purchaseinfo', this.data.purchaseinfo);
    my.alert({
      title: '添加成功',
    });
  },
  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({ closeVisible: true });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        //关联项暂时所有人可见，后续有需要再修改。
        GetPurchaseRequest((res) => {
          const cacheData = res.data.map(it => {
            it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
            return it
            // if (it.item1.corpId === storage.data.result.userid) {
            //   it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
            //   return it
            // }
          })
          this.setData({
            DisProcurementData: compact(cacheData).reverse()
          })
          console.log('data',res.data);
          console.log('annex',this.data.DisProcurementData);
        })
      }
    })
  },


  handleOk1(date, format, e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        DeliveryTime: date
      },
    })
  },
  onDescriptionChange(value) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        Description: value
      }
    })
  },
  onProcurTypeChange(value) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcurType: value
      }
    })
  },
  onProcurementDetailsChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcurementDetails: e
      }
    })
  },
  onProcurNameChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        ProcurName: e
      }
    })
  },
  onPurchaseQuantityChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        PurchaseQuantity: e
      }
    })
  },
  onUnitChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        Unit: e
      }
    })
  },
  onUnitPriceChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        UnitPrice: e,
        // Sum:calculateSum(this.data.purchaseinfo)
        Sum:e * this.data.purchaseinfo.PurchaseQuantity
      }
    })
  },
  onnotesChange(e) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        notes: e
      }
    })
  },
  handleChange(value) {
    this.setData({
      purchaseinfo: {
        ...this.data.purchaseinfo,
        PaymentMethod: value
      }
    });
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetProcurementConfirmation((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex);
                return it;
              }
            });
            resolve(cacheData);
          });
        }).then((cacheData) => {
          const updatedResPromises = cacheData.map(it => {
            // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
            const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
            it.item3 = []
            if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
              // 对每个 associateId 获取 Topic  
              return Promise.all(associateIds.map(associateId => {
                return new Promise((resolve) => {
                  GetPurchaseRequestById(associateId, (TopicRes) => {
                    it.item3.push(TopicRes.data.item1)
                    resolve(it);
                  });
                });
              })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
            } else {
              // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
              return Promise.resolve(it);
            }
          });
          // 等待所有 Promise 完成  
          return Promise.all(updatedResPromises).then(updatedRes => {
            this.setData({
              purchaseinfo: {
                ...this.data.purchaseinfo,
                CorpId: storage.data.result.userid
              },
              ReceiveData: compact(updatedRes).reverse()
            });
          });
        });
      }
    });
  },
  // 上传数据
  onSubmit(e) {
    PostProcurementConfirmation(JSON.stringify(this.data.purchaseinfo),
      (res) => {
        my.getStorage({
          key: 'userInfo',
          success: (storage) => {
            new Promise((resolve) => {
              GetProcurementConfirmation((res) => {
                const cacheData = res.data.map(it => {
                  if (it.item1.corpId === storage.data.result.userid) {
                    it.item1['displayAnnex'] = JSON.parse(it.item1.annex);
                    return it;
                  }
                });
                resolve(cacheData);
              });
            }).then((cacheData) => {
              const updatedResPromises = cacheData.map(it => {
                // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
                const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
                it.item3 = []
                if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
                  // 对每个 associateId 获取 Topic  
                  return Promise.all(associateIds.map(associateId => {
                    return new Promise((resolve) => {
                      GetPurchaseRequestById(associateId, (TopicRes) => {
                        it.item3.push(TopicRes.data.item1)
                        resolve(it);
                      });
                    });
                  })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
                } else {
                  // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
                  return Promise.resolve(it);
                }
              });
              // 等待所有 Promise 完成  
              return Promise.all(updatedResPromises).then(updatedRes => {
                this.setData({
                  purchaseinfo: {
                    ...this.data.purchaseinfo,
                    CorpId: storage.data.result.userid
                  },
                  ReceiveData: compact(updatedRes).reverse()
                });
              });
            });
          }
        });
        my.alert({
          title: '提交成功',
        });
        // GetProcurementConfirmationById(res.data, (res) => {
        //   this.setData({
        //     ReceiveData: compact([...this.data.ReceiveData, res.data].map(it => {
        //       if (it.item1.corpId === this.data.purchaseinfo.CorpId) {
        //         it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
        //         return it
        //       }
        //     })).reverse()
        //   })
        // })
        this.setData({
          purchaseinfo: {
            ...this.data.purchaseinfo,
            Description: '',//采购项目说明
            ProcurType: '办公用品',//采购类型
            DeliveryTime: '',//交付时间
            ProcurementDetails: '', //采购明细
            ProcurName: '',//名称
            PurchaseQuantity: '',//数量
            Unit: '',//单位
            Sum:'',
            UnitPrice: '', //单价
            PaymentMethod: '公对公', //支付方式
            AssociateOtherId: '[]',//关联ID
            Annex: '[]'//采购结果报告
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },
  //上传文件
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      file: { spaceId: SPACEID, max: 9, folderId: '' },
      types: ['photo', 'file'],
      success: (res) => {
        const srcAnnex = this.data.purchaseinfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))
        this.setData({
          displaydata: imageAnnex,
          purchaseinfo: {
            ...this.data.purchaseinfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },


});

function deepMergeObjects(target, source) {
  if (!isObject(target) || !isObject(source)) {
    return source; // 如果任一参数不是对象，直接返回源对象  
  }

  for (const key in source) {
    if (isObject(source[key])) {
      // 如果源对象的属性是对象，递归合并  
      if (!target[key]) {
        Object.assign(target, { [key]: {} });
      }
      deepMergeObjects(target[key], source[key]);
    } else if (Array.isArray(source[key])) {
      // 如果源对象的属性是数组，合并数组  
      if (!Array.isArray(target[key])) {
        target[key] = [];
      }
      target[key] = target[key].concat(source[key]);
    } else {
      // 对于基本类型和字符串，进行合并  
      if (['procurType', 'annex'].includes(key) && target[key] !== undefined) {
        // 如果属性名在 ['procurType', 'annex'] 中，并且目标对象中已经存在该属性，则重命名  
        const newName = `${key}1`;
        target[newName] = source[key];
      } else {
        // 否则直接赋值  
        target[key] = source[key];
      }
    }
  }

  return target;
}

function isObject(item) {
  return item && typeof item === 'object' && !Array.isArray(item);
}
function calculateSum(purchaseInfo) {  
  const unitPrice = parseFloat(purchaseInfo.UnitPrice) || 0; // 如果转换失败，默认为0  
  const purchaseQuantity = parseFloat(purchaseInfo.PurchaseQuantity) || 0; // 如果转换失败，默认为0  
  
  // 计算Sum  
  const sum = unitPrice * purchaseQuantity;  
  console.log('sum',sum);
  return sum;  
}